package com.clf.springBoot.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description RequestViewMappingInterceptor
 * @Author chenglongfei
 * @Date 2022/7/5 10:28
 */
@Component
public class RequestViewMappingInterceptor implements HandlerInterceptor {

    public final static Logger LOGGER = LoggerFactory.getLogger(RequestViewMappingInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        LOGGER.debug("======== Pre Interceptor =========");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        LOGGER.debug("======== Post Interceptor =========");

        // 判断是否是接口、redirect、forward
        if (modelAndView == null ||
                modelAndView.getViewName().startsWith("redirect") ||
                modelAndView.getViewName().startsWith("forward")) {
            return;
        }

        // 获取请求路径
        String path = request.getServletPath();

        // 获取 modelMap 中 template
        String template = (String) modelAndView.getModelMap().get("template");

        // 如果 template 为空，才将请求路径设置到 modelMap 里面
        if (StringUtils.isBlank(template)) {
            if (path.startsWith("/")) {
                path = path.substring(1);
            }
            modelAndView.getModelMap().addAttribute("template", path);
        }

        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        LOGGER.debug("======== After Interceptor =========");
    }
}